package com.cz.run.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cz.run.beans.base.PageDTO;
import com.cz.run.beans.base.ReturnDTO;
import com.cz.run.beans.mysql.*;
import com.cz.run.beans.po.product.ExchangePO;
import com.cz.run.beans.vo.product.PrizeProductVO;
import com.cz.run.beans.vo.product.ProductVO;
import com.cz.run.constants.ConstantKey;
import com.cz.run.enums.SystemCodeEnum;
import com.cz.run.service.*;
import com.cz.run.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: TODO()
 * @auther:CAIYJ
 * @Date:2018/5/27 20:38
 */
@Api(value = "商品")
@RestController
@RequestMapping(value = "/product")
public class ProductServer {

    @Autowired
    private IProductService productService;

    @Autowired
    private IUserBaseService userBaseService;

    @Autowired
    private IUserPointService userPointService;

    @Autowired
    private IUserTradeRecordService userTradeRecordService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IDeliveryAddressService deliveryAddressService;

    @Autowired
    private IProductExchangeRecordService iProductExchangeRecordService;

    @Autowired
    private IProductLuckDrawService iProductLuckDrawService;

    @ApiOperation(value = "商品列表", notes = "商品列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/list")
    public ReturnDTO<PageDTO<ProductVO>> list(@RequestBody PageDTO pageDTO) throws Exception {
        Page<Product> page = new Page<>(pageDTO.getCurrentPage(), pageDTO.getPageSize());
        EntityWrapper<Product> pew = new EntityWrapper<>();
        pew.where("type={0} and status != {1}",1,1);
        page = productService.selectPage(page,pew);
        if (null != page && null != page.getRecords() && page.getRecords().size() > 0) {
            List<ProductVO> list = new ArrayList<>();
            ProductVO vo = null;
            for (Product product : page.getRecords()) {
                vo = new ProductVO();
                BeanUtils.copyProperties(product, vo);
                list.add(vo);
            }
            pageDTO.setContent(list);
        }
        pageDTO.setTotalRecord(page.getTotal());
        return ReturnDTO.success(pageDTO);
    }

    @ApiOperation(value = "抽奖商品列表", notes = "商品列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/prizeList")
    public ReturnDTO<PageDTO<PrizeProductVO>> prizeList(@RequestBody PageDTO pageDTO) throws Exception {
        Page<Product> page = new Page<>(pageDTO.getCurrentPage(), pageDTO.getPageSize());
        EntityWrapper<Product> pew = new EntityWrapper<>();
        pew.where("type={0} and status != {1}",2,1);
        page = productService.selectPage(page,pew);
        if (null != page && null != page.getRecords() && page.getRecords().size() > 0) {
            List<PrizeProductVO> list = new ArrayList<>();
            PrizeProductVO vo = null;
            for (Product product : page.getRecords()) {
                vo = new PrizeProductVO();
                BeanUtils.copyProperties(product, vo);
                EntityWrapper<ProductLuckDraw> luew = new EntityWrapper<>();
                luew.where("product_id = {0}",product.getId());
                ProductLuckDraw productLuckDraw =iProductLuckDrawService.selectOne(luew);
                if(null!=productLuckDraw)
                vo.setTime(DateUtil.currentTimeMillisCN1(productLuckDraw.getPrizeTime()));

                list.add(vo);
            }
            pageDTO.setContent(list);
        }
        pageDTO.setTotalRecord(page.getTotal());
        return ReturnDTO.success(pageDTO);
    }

    @ApiOperation(value = "兑换商品", notes = "兑换商品", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/exchange")
    @Transactional
    public ReturnDTO exchange(@RequestBody ExchangePO po, HttpServletRequest request) throws Exception {
        if (po.getProductId() == null) {
            return ReturnDTO.fail(SystemCodeEnum.error_invalid_argument);
        }
        String userId = (String) request.getAttribute(ConstantKey.USER_KEY);
        Product product = productService.selectById(po.getProductId());
        if (null == product) {
            if (product.getStatus() == 0) {
                return ReturnDTO.error("该商品为预售商品，敬请期待");
            }
            if (product.getStock() <= 0 || product.getStatus() == 1 || product.getStock() < po.getNum()) {
                return ReturnDTO.error("该商品货存不足！请联系客服");
            }
        }

        EntityWrapper<Order> oew = new EntityWrapper<>();
        oew.where("product_id = {0}",po.getProductId());
        oew.and("user_id = {0}",userId);
        String[] status = {"1", "2", "3"};
        oew.in("order_status", status);
        List<Order> orders = orderService.selectList(oew);
        if (null != orders && orders.size() > 0){
            return ReturnDTO.error("您已兑换过该商品！");
        }

        EntityWrapper<UserPoint> ew = new EntityWrapper<>();
        ew.where("user_id = {0}", userId);
        UserPoint userPoint = userPointService.selectOne(ew);
        if (userPoint != null) {
            if (((userPoint.getPoint() != null ? userPoint.getPoint() : 0) - (userPoint.getPointFrozen() != null ? userPoint.getPointFrozen() : 0)) < (product.getIntegral() != null ? product.getIntegral() : 0) * (po.getNum() != null ? po.getNum() : 0)) {
                return ReturnDTO.error("您的积分不足！");
            }
            EntityWrapper<DeliveryAddress> dew = new EntityWrapper<>();
            dew.where("user_id = {0}", userId);
            List<DeliveryAddress> list = deliveryAddressService.selectList(dew);
            if (null == list || list.size() == 0) {
                return ReturnDTO.error("收货地址未填，请补充");
            }
            double point = userPoint.getPoint() - (product.getIntegral() != null ? product.getIntegral() : 0) * (po.getNum() != null ? po.getNum() : 0);
            UserTradeRecord userTradeRecord = new UserTradeRecord();
            userTradeRecord.setAddress("system");
            userTradeRecord.setTradeTime(new Date());
            userTradeRecord.setType("2");
            userTradeRecord.setPoint((product.getIntegral() != null ? product.getIntegral() : 0) * (po.getNum() != null ? po.getNum() : 0));
            userTradeRecord.setUserId(Integer.parseInt(userId));
            userTradeRecordService.insert(userTradeRecord);
            userPoint.setPoint(point);
            userPointService.updateById(userPoint);
            Order order = new Order();
            order.setProductId(po.getProductId());
            order.setProductCount(po.getNum());
            order.setOrderStatus(1);
            order.setProductAmountTotal((product.getIntegral() != null ? product.getIntegral() : 0) * (po.getNum() != null ? po.getNum() : 0));
            order.setOrderAmountTotal(new BigDecimal((product.getIntegral() != null ? product.getIntegral() : 0) * (po.getNum() != null ? po.getNum() : 0)));
            order.setUserId(Integer.parseInt(userId));
            order.setAddressId(list.get(0).getId());
            order.setPayTime(new Date());
            orderService.insert(order);
        } else {
            return ReturnDTO.error("账户信息异常");
        }

        ProductExchangeRecord productExchangeRecord = new ProductExchangeRecord();
        productExchangeRecord.setCreateTime(new Date());
        productExchangeRecord.setIntegral(po.getNum()*product.getIntegral());
        productExchangeRecord.setProductCount(po.getNum());
        productExchangeRecord.setProductId(po.getProductId());
        productExchangeRecord.setUserId(Integer.parseInt(userId));
        iProductExchangeRecordService.insert(productExchangeRecord);
        return ReturnDTO.success("消费成功");
    }
}
